<template>
  <div>
    <div class="search">
      <Row>
        <Col>
          <Card>
            <Row>
              <Form ref="searchForm" :model="searchForm" inline :label-width="100" class="search-form">
                <Form-item label="项目名称" prop="">
                  <Input v-model="searchForm.project_name" style="width: 260px;"/>
                </Form-item>
                <Form-item style="margin-left:-100px;" class="br">
                  <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                  <Button @click="handleReset">重置</Button>
                </Form-item>
              </Form>
            </Row>
            <Row class="operation">
              <Button @click="addFirstTicket" type="primary" icon="md-add">添加工作票</Button>
              <Button @click="editFirstTicket" type="warning" icon="ios-bookmarks-outline" >编辑工作票</Button>
              <Button @click="viewFirstTicket" type="success" icon="ios-eye" >查看工作票</Button>
              <Button @click="deleteFirstTicket" type="error" icon="md-alert" >删除工作票</Button>
              <Button @click="refresh" icon="refresh">刷新</Button>
            </Row>
            <Row>
              <Alert show-icon>
                已选择 <span class="select-count">{{selectCount}}</span> 项
                <a class="select-clear" @click="clearSelectAll">清空</a>
              </Alert>
            </Row>
            <Row>
              <Table
                border
                :loading="loading"
                :columns="columns"
                :data="data"
                sortable="custom"
                @on-selection-change="showSelect"
                ref="table">
              </Table>
              <Table :columns="exportColumns" :data="exportData" ref="exportTable" style="display:none"></Table>
            </Row>
            <Row type="flex" justify="end" class="page">
              <Page
                :current="searchForm.pageNumber"
                :total="total"
                :page-size="searchForm.pageSize"
                @on-change="changePage"
                @on-page-size-change="changePageSize"
                :page-size-opts="[10,20,50]"
                size="small"
                show-total
                show-elevator
                show-sizer
              ></Page>
            </Row>
          </Card>
        </Col>
      </Row>
      <editTicket :data="form" v-model="editVisiable" @on-submit="refresh"/>
      <viewFirstTicket :data="viewForm" v-model="viewVisiable"  @on-submit="refresh"/>
      <Modal title="添加配电第一种工作票" v-model="addTicketVisible" :mask-closable='false' :width="500" :styles="{top: '60px'}">
        <Form ref="ticketForm" :model="ticketForm" :label-width="100" :rules="ticketFormValidate">
          <FormItem label="归属项目名称" prop="project_id" >
            <Select v-model="ticketForm.project_id" clearable filterable>
                <Option v-for="item in projectNameList" :value="item.id" :key="item.id">{{ item.project_name }}</Option>
            </Select>
          </FormItem>
          <FormItem label="工作票编号" prop="ticket_code" >
              <Input v-model="ticketForm.ticket_code" placeholder=""/>
          </FormItem>
          <FormItem label="施工单位" prop="ticket_unit" >
              <Input v-model="ticketForm.ticket_unit" placeholder="请输入施工单位"/>
          </FormItem>
          <FormItem label="工作负责人" prop="work_leader" >
              <Input v-model="ticketForm.work_leader" placeholder="请输入工作负责人"/>
          </FormItem>
        </Form>
        <div slot="footer">
            <Button type="text" @click="cancelTicket">取消</Button>
            <Button type="primary" :loading="submitLoading" @click="submitTicket">提交</Button>
        </div>
      </Modal>
    </div>
  </div>
</template>
<script>
import { getFirstTicket, destroyDispatch, getProjectName, insertFirstTicket, getFirstTicketById } from '@/api/work';
import util from '@/libs/util';
import moment from 'moment';
import editTicket from './edit';
// import addEdit from './addEdit';
import viewFirstTicket from './view';
export default {
  name: 'firstTicket-manager',
  components: {
    viewFirstTicket,
    editTicket
  },
  data() {
    const validateProjectName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('工程名称必须选择'))
      } else {
        callback();
      }
    };
    return {
      loading: false,
      searchForm: {
        project_name: '',
        pageNumber: 1,
        pageSize: 10
      },
      data: [],
      total: 0,
      selectCount: 0,
      exportData: [],
      selectList: [],
      exportColumns: [],
      columns: [
        {
          type: "selection",
          width: 50,
          align: "center",
          fixed: "left"
        },
        {
          type: "index",
          width: 50,
          align: "center",
          fixed: "left"
        },
        {
          title: '工作票编号',
          key: 'ticket_code',
          width: 140,
          align: 'center'
        },
        {
          title: '项目编号',
          key: 'project_code',
          width: 150,
        },
        {
          title: '项目名称',
          key: 'project_name',
          width: 220,
        },
        {
          title: '施工单位',
          key: 'ticket_unit',
          width: 280,
        },
        {
          title: '工作票签发人',
          key: 'ticket_signer',
          width: 100,
          align: 'center'
        },
        {
          title: '工作负责人',
          key: 'work_leader',
          width: 100,
          align: 'center'
        },
        {
          title: '工作许可人',
           key: 'work_licensor',
          width: 100,
          align: 'center'
        },
        {
            title: "状态",
            key: "state",
            align: "center",
            width: 60,
            render: (h, params) => {
              let re = "";
              if (params.row.state === 0) {
                re = "草稿";
              } else if (params.row.state === 1) {
                re = "已签发";
              } else if (params.row.state === 2) {
                re = "已执行";
              }
              return h("div", re);
            }
          },
      ],
      editVisiable: false,
      viewVisiable: false,
      addTicketVisible: false,
      form: {},
      showType: '0',
      viewForm: {},
      submitLoading: false,
      projectNameList: [],
      ticketForm: {},
      ticketFormValidate: {
        project_id: [
          {validator: validateProjectName, trigger: "blur"}
        ],
        ticket_code: [
          {required: true, message: "工作票编号不能为空", trigger: "blur"},
        ],
        ticket_unit: [
          {required: true, message: "施工单位不能为空", trigger: "blur"}
        ],
        work_leader: [
          {required: true, message: "工作负责人不能为空", trigger: "blur"}
        ],
      },
    }
  },
  methods: {
    getFirstTicketList() {
      this.loading = true;
      getFirstTicket(this.searchForm).then(res => {
        this.loading = false;
        if (res.code === 0) {
          this.data = res.data.rows;
          this.total = res.data.count;
        }
      })
    },
    getProjects() {
      getProjectName().then(res => {
        if (res.code === 0) {
          this.projectNameList = res.data.raws;
        }
      })
    },
    init() {
      this.getFirstTicketList();
      this.getProjects();
    },
    handleSearch() {
      this.searchForm.project_name = this.searchForm.project_name.trim();
      if (this.searchForm.project_name.length > 0) {
        this.searchForm.pageNumber = 1;
        this.getFirstTicketList();
      } else {
        this.$Message.warning('请输入要搜索的项目名称！');
        return;
      }
    },
    handleReset() {
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.getFirstTicketList();
    },
    addFirstTicket() {
      const hasPermission = util.oneOf('add', this.$route.meta.permTypes);
      if (!hasPermission) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      }; 
      this.addTicketVisible = true;
    },
    cancelTicket() {
      this.ticketForm = {};
      this.addTicketVisible = false;
    },
    // 新增工作票确认
    submitTicket() {
      this.$refs.ticketForm.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          insertFirstTicket(this.ticketForm).then(res => {
            this.submitLoading = false;
            if (res.code === 0) {
              this.$Message.success(res.message);
              this.addTicketVisible = false;
              this.getFirstTicketList();
            }
          })
        }
      })
    },
    editFirstTicket() {
      const hasPermission = util.oneOf('edit', this.$route.meta.permTypes);
      if (!hasPermission) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      }; 
      if (this.selectList.length !== 1) {
        this.$Message.warning('必须选择一条记录进行操作!');
        return;
      }
      const first_ticket_id = this.selectList[0].id;
      getFirstTicketById({first_ticket_id}).then(res => {
        if (res.code === 0) {
          this.form = res.data;
          console.log(res)
          this.editVisiable = true;
        }
      })
    },
    viewFirstTicket() {
      const hasPermission = util.oneOf('view', this.$route.meta.permTypes);
      if (!hasPermission) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      }; 
      if (this.selectList.length !== 1) {
        this.$Message.warning('必须选择一条记录进行操作!');
        return;
      }
      const first_ticket_id = this.selectList[0].id;
      getFirstTicketById({first_ticket_id}).then(res => {
        if (res.code === 0) {
          this.viewForm = res.data;
          // console.log(res)
          this.viewVisiable = true;
        }
      })
    },
    deleteFirstTicket() {
      const hasPermission = util.oneOf('delete', this.$route.meta.permTypes);
      if (!hasPermission) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      }; 
      if (this.selectList.length !== 1) {
        this.$Message.warning('必须选择一条记录进行操作!');
        return;
      }
      if (this.selectList[0].state === 1) {
        this.$Message.warning('此派车单已经审批过了，不允许删除!');
        return;
      }
      this.$Modal.confirm({
        title: '确认删除',
        content: '删除不可恢复，你确认要删除'+this.selectList[0].project_name+'工程的这张派车单吗？',
        onOk: () => {
          destroyDispatch({id: this.selectList[0].id}).then(res => {
            if (res.code === 0) {
              this.$Message.success(res.message);
              this.getFirstTicketList();
            }
          })
        }
      });
    },
    refresh() {
      this.getFirstTicketList();
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false);
    },
    showSelect(e) {
      this.exportData = e;
      this.selectList = e;
      this.selectCount = e.length;
    },
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getFirstTicketList();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.getFirstTicketList();
    },
  },
  mounted() {
    this.init();
  }
}
</script>
<style lang="less" scoped>
@import "./firstTicketManager.less";
</style>